﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using System.Linq;
using LdExpress;
using System.IO;
using System.Collections.Generic;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./PricingRoadForSales.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 20;
    public string strPager = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    public string strExcluded = "ID";
    public string strPartQuery = "";
    protected void Page_Load(object sender, EventArgs e)
    {

        int nPage = 1;
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;

        if ((Session["logined_id"] != null) && (int.Parse(Session["logined_id"].ToString()) > 0))
        {
            if (Session["PricingRoadForSales"] != "") nPermissions = int.Parse(Session["PricingRoadForSales"].ToString());
        }
        else
            Response.Redirect("Login.aspx");



        if (!Page.IsPostBack)
        {
            LoadSearch();
            LoadUserSearch();
            if (nPermissions >= 9)
            {
                LoadLocationSearch();

            }
            else
            {
                ddLocationSearch.Visible = false;
            }
            CommonFunctions.GetAllQueryString(Request, "", "action;ID", out strPartQuery);
            if (Request.QueryString["action"] == "delete" && nPermissions > 7)
            {
                PricingRoadForSales obj = new PricingRoadForSales();
                obj.ID = long.Parse(Request.QueryString["ID"].ToString());
                obj.Delete(GV.cn, GV.trans);
                Response.Redirect("PricingRoadForSales.aspx" + strPartQuery);
            }

            #region Build List
            int nNumOfPages = 0;

            DataTable dtList;
            BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
            if (nPage > nNumOfPages) nPage = 1;

            rptData.DataSource = dtList;
            rptData.DataBind();
            #endregion
            #region Build Pager
            CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
            #endregion
        }

    }
    private void BuildList(string strCondition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Index");
        dtList.Columns.Add("ID");
        dtList.Columns.Add("DistrictName");//Factory
        dtList.Columns.Add("LocationName");//Port
        dtList.Columns.Add("Kms");//Kms depend District and Location in HuyenTable
        dtList.Columns.Add("ContRequest1");
        dtList.Columns.Add("ContRequest2");
        dtList.Columns.Add("UserRequest");
        dtList.Columns.Add("UpdateTimeRequest");
        dtList.Columns.Add("Targeted");
        dtList.Columns.Add("UserResponse");
        dtList.Columns.Add("Cont20");
        dtList.Columns.Add("VndKm20");
        dtList.Columns.Add("Cont40");
        dtList.Columns.Add("VndKm40");    //Vnd/Km
        dtList.Columns.Add("TruckerName");
        dtList.Columns.Add("Suare");
        dtList.Columns.Add("Note_Response");
        dtList.Columns.Add("Bkg");
        dtList.Columns.Add("Idea");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;
        string sqlCommand = "";

        if (Session["PricingRoadFrom"] != null && Session["PricingRoadFrom"].ToString() != "")
        {
            DateTime dt = DateTime.ParseExact(Session["PricingRoadFrom"].ToString(), "dd-MM-yyyy",
                                  CultureInfo.InvariantCulture);
            dt = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0);
            strCondition += " AND UpdateTimeRequest>='" + dt.ToString("yyyy-MM-dd HH:mm:ss") + "'";
        }
        if (Session["PricingRoadTo"] != null && Session["PricingRoadTo"].ToString() != "")
        {
            DateTime dt = DateTime.ParseExact(Session["PricingRoadTo"].ToString(), "dd-MM-yyyy",
                                  CultureInfo.InvariantCulture);
            dt = new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 0);
            strCondition += " AND UpdateTimeRequest<='" + dt.ToString("yyyy-MM-dd HH:mm:ss") + "'";
        }
        if (Session["PricingRoadLocation"] != null && Session["PricingRoadLocation"].ToString() != "")
        {
            strCondition += " AND ToID =" + Session["PricingRoadLocation"].ToString();
        }
        if (Session["PricingRoadUser"] != null && Session["PricingRoadUser"].ToString() != "")
        {
            strCondition += " AND UserIDRequest =" + Session["PricingRoadUser"].ToString();
        }

        PricingRoadForSales.GetList(strCondition, "UpdateTimeRequest DESC", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);
        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                count++;
                string Index = count.ToString();
                string ID = dr["ID"].ToString();
                string DistrictName = DBModule.ucFirstAllWords(dr["DistrictName"].ToString().ToLower()) + ", " + dr["ProvinceName"].ToString();
                string LocationName = dr["LocationName"].ToString();
                string ContRequest1 = dr["ContRequest1"].ToString();
                string ContRequest2 = dr["ContRequest2"].ToString();
                string UserRequest = dr["UserRequest"].ToString();
                string UpdateTimeRequest = DateTime.Parse(dr["UpdateTimeRequest"].ToString()).ToString("dd/MM/yyyy HH:mm");
                string UserResponse = dr["UserResponse"].ToString();
                string Cont20 = dr["Cont20"].ToString();
                if ((ContRequest1 == "Cont20" || ContRequest2 == "Cont20") && Cont20 == "") Cont20 += " X";
                string Cont40 = dr["Cont40"].ToString();
                if ((ContRequest1 == "Cont40" || ContRequest2 == "Cont40") && Cont40 == "") Cont40 += " X";
                float Distance = Huyen.Distance(long.Parse(dr["ExID"].ToString()), long.Parse(dr["ToID"].ToString()));
                string Kms = Distance > 0 ? Distance.ToString("#,0.##") : "";
                float fvndKm20 = 0, fvndKm40 = 0;
                string VndKm20 = "", VndKm40 = "";
                if (Distance > 0)
                {
                    try
                    {
                        fvndKm20 = float.Parse(Cont20.Split('_')[0]) / Distance;
                    }
                    catch { }
                    try
                    {
                        fvndKm40 = float.Parse(Cont40.Split('_')[0]) / Distance;
                    }
                    catch { }
                    if (fvndKm20 > 0)
                    {
                        VndKm20 = fvndKm20.ToString("#,0.##");
                    }
                    if (fvndKm40 > 0)
                    {
                        VndKm40 = fvndKm40.ToString("#,0.##");
                    }
                }

                string TruckerName = dr["TruckerName"].ToString();
                int nSuare = int.Parse(dr["Suare"].ToString());
                string strSuare = "<img src='Assets/images/star_0.gif'/><img src='Assets/images/star_0.gif'/><img src='Assets/images/star_0.gif'/>";
                if (nSuare == 1)
                    strSuare = "<img src='Assets/images/star_1.gif'/><img src='Assets/images/star_0.gif'/><img src='Assets/images/star_0.gif'/>";
                else if (nSuare == 2)
                    strSuare = "<img src='Assets/images/star_1.gif'/><img src='Assets/images/star_1.gif'/><img src='Assets/images/star_0.gif'/>";
                else if (nSuare == 3)
                    strSuare = "<img src='Assets/images/star_1.gif'/><img src='Assets/images/star_1.gif'/><img src='Assets/images/star_1.gif'/>";
                string Suare = strSuare;
                string Note_Response = dr["Note_Response"].ToString();
                string Bkg = dr["Bkg"].ToString();
                string Targeted = dr["Targeted"].ToString();
                string Idea = dr["Idea"].ToString();
                string Action = "";
                if (nPermissions >= 3)
                {
                    Action += " <a href=\"javascript:doEdit('" + ID.ToString() + "')\">" + "Edit</a>";
                    string DayEditable = GeneralSetting.GetValueByCode("PR_ROAD_FOR_SALES_NOT_EDIT", GV.cn, GV.trans);
                    int nDayEditable = 7;
                    if (DayEditable != null)
                    {
                        try
                        {
                            nDayEditable = int.Parse(DayEditable);
                        }
                        catch { }
                    }
                    if (DateTime.Now <= DateTime.Parse(dr["UpdateTimeRequest"].ToString()).AddDays(nDayEditable))
                    {
                        Action += " - <a href=\"javascript:doRefer('" + ID.ToString() + "'," + dr["ExID"].ToString() + "," + dr["ToID"].ToString() + ")\">" + "Rate</a>";
                    }
                }
                if (nPermissions > 7)
                {
                    Action += " - <a href=\"javascript:doDelete('" + ID.ToString() + "')\">" + "Del</a>";
                }

                string[] strValues = new string[] {
                            Index,
                            ID , 
                            DistrictName,
                            LocationName,
                            Kms,
                            ContRequest1,
                            ContRequest2,
                            UserRequest,
                            UpdateTimeRequest,
                            Targeted,
                            UserResponse,
                            Cont20,
                            VndKm20,
                            Cont40,
                            VndKm40,
                            TruckerName,
                            Suare,
                            Note_Response,
                            Bkg,
                            Idea,
                            Action };
                dtList.Rows.Add(strValues);

            }
        }
    }
    protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        CheckBox cb = (CheckBox)e.Item.FindControl("cbBkg");
        HiddenField hidBkg = (HiddenField)e.Item.FindControl("hidBkg");
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            try
            {
                if (hidBkg.Value == "1")
                    cb.Checked = true;
                cb.Enabled = false;
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
        CheckBox cbTargeted = (CheckBox)e.Item.FindControl("cbTargeted");
        HiddenField hidTargeted = (HiddenField)e.Item.FindControl("hidTargeted");
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            try
            {
                if (hidTargeted.Value == "1")
                    cbTargeted.Checked = true;
                cbTargeted.Enabled = false;
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        if (txtFrom.Text.ToLower() != "from")
            Session["PricingRoadFrom"] = txtFrom.Text;
        else
            Session["PricingRoadFrom"] = "";

        if (txtTo.Text.ToLower() != "to")
            Session["PricingRoadTo"] = txtTo.Text;
        else
            Session["PricingRoadTo"] = "";
        Response.Redirect("PricingRoadForSales.aspx");
    }
    public void LoadSearch()
    {
        if (Session["PricingRoadFrom"] == null)
            Session["PricingRoadFrom"] = DateTime.Now.AddDays(-14).ToString("dd-MM-yyyy");
        if (Session["PricingRoadTo"] == null)
            Session["PricingRoadTo"] = DateTime.Now.ToString("dd-MM-yyyy");
        if (Session["PricingRoadFrom"] != null)
            txtFrom.Text = Session["PricingRoadFrom"].ToString();
        if (Session["PricingRoadTo"] != null)
            txtTo.Text = Session["PricingRoadTo"].ToString();
    }
    protected void LoadLocationSearch()
    {

        DataSet ds;
        Location.DoSearch("", "Name", out ds, GV.cn, GV.trans);
        DataTable dt = ds.Tables[0];
        //Location Search
        ddLocationSearch.Items.Add((new ListItem("-- Location --", "")));
        ddLocationSearch.AppendDataBoundItems = true;
        ddLocationSearch.DataSource = dt;
        ddLocationSearch.DataTextField = dt.Columns["Name"].ToString();
        ddLocationSearch.DataValueField = dt.Columns["ID"].ToString();
        ddLocationSearch.DataBind();
        if (Session["PricingRoadLocation"] != null)
        {
            if (ddLocationSearch.Items.FindByValue(Session["PricingRoadLocation"].ToString()) != null)
                ddLocationSearch.SelectedValue = Session["PricingRoadLocation"].ToString();
        }
    }
    protected void ddLocationSearch_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["PricingRoadLocation"] = ddLocationSearch.SelectedValue;
        Response.Redirect("PricingRoadForSales.aspx");
    }
    protected void LoadUserSearch()
    {

        DataSet ds;
        string SqlCommand = "Select ID,UserName From tbl_AdminUsers where ID in(SELECT DISTINCT UserIDRequest FROM tbl_PricingRoadForSales)";
        if (nPermissions < 9)
            SqlCommand += " AND ID=" + Session["logined_id"].ToString();
        ds = DBModule.ExecuteQuery(SqlCommand, GV.cn, GV.trans);
        DataTable dt = ds.Tables[0];
        //Location Search
        ddUser.Items.Add((new ListItem("-- User --", "")));
        ddUser.AppendDataBoundItems = true;
        ddUser.DataSource = dt;
        ddUser.DataTextField = dt.Columns["UserName"].ToString();
        ddUser.DataValueField = dt.Columns["ID"].ToString();
        ddUser.DataBind();
        if (Session["PricingRoadUser"] != null)
        {
            if (ddUser.Items.FindByValue(Session["PricingRoadUser"].ToString()) != null)
                ddUser.SelectedValue = Session["PricingRoadUser"].ToString();
        }
    }
    protected void ddUser_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["PricingRoadUser"] = ddUser.SelectedValue;
        Response.Redirect("PricingRoadForSales.aspx");
    }
    public string GetNoticeClass(object TimeRequest, object oDC20, object oDC40)
    {
        string result = "";
        if (TimeRequest != null)
        {
            string DC20 = oDC20.ToString().Trim() == "X" ? "" : oDC20.ToString();
            string DC40 = oDC40.ToString().Trim() == "X" ? "" : oDC40.ToString();
            if (DC20.ToString() == "" && DC40.ToString() == "")
            {
                IFormatProvider culture = new CultureInfo("vi-VN", true);
                DateTime dt = DateTime.Parse(TimeRequest.ToString(), culture);
                DateTime currTime = DateTime.Now;
                if (currTime >= dt.AddHours(8))// Mau do
                    result = "notice8hour";
                else if (currTime >= dt.AddHours(4))// Mau tim
                    result = "notice4hour";
                else if (currTime >= dt.AddHours(2))// Mau cam
                    result = "notice2hour";
            }
        }
        return result;
    }
}
